package com.ly.heart.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ly.common.core.domain.AjaxResult;
import com.ly.common.core.domain.entity.SysDept;
import com.ly.common.core.domain.entity.SysUser;
import com.ly.common.exception.CustomException;
import com.ly.common.utils.DateUtils;
import com.ly.common.utils.SecurityUtils;
import com.ly.common.utils.erp.ConstUtil;
import com.ly.common.utils.erp.SnowflakeIdWorker;
import com.ly.heart.domain.*;
import com.ly.heart.domain.dto.KingPayableVerificationDto;
import com.ly.heart.domain.vo.KingPayableVerificationVo;
import com.ly.heart.mapper.KingPayableReceivableVerificationMapper;
import com.ly.heart.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.heart.util.ChineseToPinyin;
import com.ly.system.service.ISysDeptService;
import com.ly.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 应付付款单核销单 服务实现类
 * </p>
 *
 * @author WuZH
 * @since 2024-08-12
 */
@Service
public class KingPayableReceivableVerificationServiceImpl extends ServiceImpl<KingPayableReceivableVerificationMapper, KingPayableReceivableVerificationEntity> implements IKingPayableReceivableVerificationService {

    @Resource
    private IKingPayableReceivableVerificationDetailService iKingPayableReceivableVerificationDetailService;
    @Resource
    private IKingInvoicePayableService iKingInvoicePayableService;
    @Resource
    private IKingInvoicePayableDetailService iKingInvoicePayableDetailService;
    @Resource
    private IKingFinancePayService iKingFinancePayService;
    @Resource
    private ISysDeptService iSysDeptService;
    @Resource
    private IKingBaseCurrencyService iKingBaseCurrencyService;
    @Resource
    private IKingFinancePayDetailService iKingFinancePayDetailService;
    @Resource
    private ISysUserService iSysUserService;
    @Resource
    private IKingFinanceReceiptService iKingFinanceReceiptService;
    @Resource
    private IKingFinanceReceiptDetailService iKingFinanceReceiptDetailService;
    @Resource
    private IKingInvoiceReceivableService iKingInvoiceReceivableService;
    @Resource
    private IKingInvoiceReceivableDetailService iKingInvoiceReceivableDetailService;

    @Override
    public AjaxResult queryList ( KingPayableReceivableVerificationEntity kingPayableReceivableVerificationEntity) {
        LambdaQueryWrapper<KingPayableReceivableVerificationEntity> lambdaQueryWrapper = new LambdaQueryWrapper<> ();
        if ( kingPayableReceivableVerificationEntity.getType () != null ) {
            lambdaQueryWrapper.eq ( KingPayableReceivableVerificationEntity :: getType, kingPayableReceivableVerificationEntity.getType () );
        }
        Page page = this.page ( new Page<> ( kingPayableReceivableVerificationEntity.getPage (), kingPayableReceivableVerificationEntity.getLimit () ), lambdaQueryWrapper );
        return AjaxResult.success ( page );
    }

    @Override
    public KingPayableVerificationVo querySingle ( String id ) {
        KingPayableVerificationVo vo = new KingPayableVerificationVo ();
        KingPayableReceivableVerificationEntity verificationEntity = this.getById ( id );
        KingPayableReceivableVerificationDetailEntity verificationDetailEntity = new KingPayableReceivableVerificationDetailEntity ();
        verificationDetailEntity.setRelationVerificationId ( id );
        List<KingPayableReceivableVerificationDetailEntity> list = iKingPayableReceivableVerificationDetailService.queryList ( verificationDetailEntity );
        verificationEntity.setKingPayableVerificationDetailEntities ( list );
        vo.setKingPayableReceivableVerificationEntity ( verificationEntity ).setKingPayableVerificationDetailEntities ( list );
        return vo;
    }

    /**
     * 自动核销和匹配核销
     *
     * @param kingPayableReceivableVerificationEntity：应付付款核销单基本数据对象
     * @param payableVerificationDetailEntities：应付付款核销单明细数据列表
     * @return
     */
    @Override
    @Transactional ( rollbackFor = Exception.class, propagation = Propagation.REQUIRED )
    public AjaxResult saveSingle (KingPayableReceivableVerificationEntity kingPayableReceivableVerificationEntity, List<KingPayableReceivableVerificationDetailEntity> payableVerificationDetailEntities ) {
        kingPayableReceivableVerificationEntity.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
        int count = this.count ();
        String py = ChineseToPinyin.getFirstLetter ( "应付付款核销单" );
        kingPayableReceivableVerificationEntity.setDocNo ( py.concat ( String.format ( "%08d", count ) ) );
        kingPayableReceivableVerificationEntity.setBizTime ( DateUtils.getNowDate () );
        SysUser user = iSysUserService.getById ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        kingPayableReceivableVerificationEntity.setVerificationName ( ObjectUtils.isEmpty ( user ) ? "" : user.getNickName () );
        kingPayableReceivableVerificationEntity.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
        kingPayableReceivableVerificationEntity.setCreateTime ( DateUtils.getNowDate () );
        // 处理明细
        updateKingPayableVerificationDetail ( payableVerificationDetailEntities, kingPayableReceivableVerificationEntity.getId () );
        boolean save = this.save ( kingPayableReceivableVerificationEntity );
        if ( ! save ) {
            throw new CustomException ( "新增应付付款核销单失败！" );
        }
        return AjaxResult.success ();
    }

    /**
     * 手工核销
     * 1、供应商、客户、币别、结算组织都相同才能核销
     *
     * @param kingPayableVerificationDto
     * @return
     */
    @Override
    public AjaxResult manualVerification ( KingPayableVerificationDto kingPayableVerificationDto ) {
        KingFinancePayEntity kingFinancePayEntity = kingPayableVerificationDto.getKingFinancePayEntity ();
        KingInvoicePayableEntity kingInvoicePayableEntity = kingPayableVerificationDto.getKingInvoicePayableEntity ();
        KingFinancePayEntity payEntity = iKingFinancePayService.querySingleById ( kingFinancePayEntity.getId () );
        KingInvoicePayableEntity payableEntity = iKingInvoicePayableService.querySingleById ( kingInvoicePayableEntity.getId () );
        if ( ObjectUtils.isEmpty ( kingFinancePayEntity ) || ObjectUtils.isEmpty ( kingInvoicePayableEntity ) ) {
            return AjaxResult.error ( "核销对象不能为空" );
        }
        if ( payEntity.getKingBaseCurrencyCode ().equals ( payableEntity.getCurrencyCode () )
                // && payEntity.getSupplierCode ().equals ( payableEntity.getSupplierCode () )
                && payEntity.getSettlementDeptId ().equals ( payableEntity.getSettlementDeptId () ) ) {
            //核销
            KingPayableReceivableVerificationEntity payableVerificationEntity = new KingPayableReceivableVerificationEntity ();
            SysDept sysDept = iSysDeptService.getById ( payEntity.getSettlementDeptId () );
            KingBaseCurrencyEntity one = iKingBaseCurrencyService.getOne ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getCode, sysDept.getStandardCurrencyCode () ) );
            payableVerificationEntity.setSettlementCompany ( sysDept.getDeptName () );
            payableVerificationEntity.setOwnCurrencyTitle ( one.getCurrencyName () );
            payableVerificationEntity.setPayReceiptCompany ( sysDept.getDeptName () );
            payableVerificationEntity.setVerificationType ( 3 );
            //2.核销列表对象
            String amount = Double.parseDouble ( payEntity.getActualMoney () ) > Double.parseDouble ( payableEntity.getTotalTaxPrice () ) ? payableEntity.getTotalTaxPrice () : payEntity.getActualMoney ();
            KingPayableReceivableVerificationDetailEntity payVerification = new KingPayableReceivableVerificationDetailEntity ();
            payVerification.setDoc ( "付款单" ).setDocType ( payEntity.getDocTypeCode () ).setDocNo ( payEntity.getDocNo () ).//setLineNumber ( payDetail.getLineNumber () ).
                    setBizTime ( payEntity.getBusinessTime () ).setTransactionDeptTitle ( payEntity.getTransactionCompanyName () ).setCurrencyTitle ( payEntity.getSettlementCurrencyName () ).
                    setRate ( payEntity.getRate () ).setVerificationAmount ( amount );//.setPayPurpose ( payDetail.getPayReceiptPurposeCode () ).setMaterialName ( payDetail.getMaterialCode () ).setFeeItem ( payDetail.getFeeCode () );
            KingPayableReceivableVerificationDetailEntity payableVerification = new KingPayableReceivableVerificationDetailEntity ();
            payableVerification.setDoc ( "应付单" ).setDocType ( payableEntity.getDocTypeCode () ).setDocNo ( payableEntity.getDocNo () ).setLineNumber ( "1" ).setBizTime ( payableEntity.getBizTime () ).
                    setTransactionDeptTitle ( payableEntity.getSupplierName () ).setCurrencyTitle ( payableEntity.getCurrencyName () ).setRate ( payableEntity.getRate () ).setVerificationAmount ( amount );
            List<KingPayableReceivableVerificationDetailEntity> payableVerificationDetailEntities = new ArrayList<> ();
            payableVerificationDetailEntities.add ( payVerification );
            payableVerificationDetailEntities.add ( payableVerification );
            saveSingle ( payableVerificationEntity, payableVerificationDetailEntities );
        }
        return AjaxResult.success ();
    }

    /**
     * 拉取改供应商的应付单和付款单，并且未核销金额大于0
     *
     * @param supperId
     * @return
     */
    @Override
    public KingPayableVerificationVo loadVerificationList ( String supperId ) {
        List<KingInvoicePayableEntity> resultPayable = new ArrayList<> ();
        List<KingFinancePayEntity> resultPay = new ArrayList<> ();
        //1.应付单列表
        List<KingInvoicePayableEntity> payableEntities = iKingInvoicePayableService.list ( new LambdaQueryWrapper<KingInvoicePayableEntity> ().
                eq ( KingInvoicePayableEntity :: getSupplierId, supperId ).
                eq ( KingInvoicePayableEntity :: getState, ConstUtil.STATE_FINISH ) );
        //2.付款单列表
        List<KingFinancePayEntity> payEntities = iKingFinancePayService.list ( new LambdaQueryWrapper<KingFinancePayEntity> ().
                eq ( KingFinancePayEntity :: getReceiptDeptId, supperId ).
                eq ( KingFinancePayEntity :: getState, ConstUtil.STATE_FINISH ) );
        //3.已核销列表
        List<String> docNos = payableEntities.stream ().map ( KingInvoicePayableEntity :: getDocNo ).collect ( Collectors.toList () );
        List<String> payNos = payEntities.stream ().map ( KingFinancePayEntity :: getDocNo ).collect ( Collectors.toList () );
        docNos.addAll ( payNos );
        List<KingPayableReceivableVerificationDetailEntity> list = iKingPayableReceivableVerificationDetailService.list ( new LambdaQueryWrapper<KingPayableReceivableVerificationDetailEntity> ().
                eq ( KingPayableReceivableVerificationDetailEntity :: getDocNo, docNos ) );
        // 筛选剩余未核销金额大于0的应付单
        payableEntities.forEach ( payable -> {
            //求当前应付单的已核销金额
            double sum = list.stream ().filter ( detail -> detail.getDocNo ().equals ( payable.getDocNo () ) ).mapToDouble ( detail -> Double.parseDouble ( detail.getVerificationAmount () ) ).sum ();
            //求应付单实际金额大于已核销金额，表示还未核销结束
            if ( Double.parseDouble ( payable.getTotalTaxPrice () ) > sum ) {
                resultPayable.add ( payable );
            }
        } );
        payEntities.forEach ( pay -> {
            double sum = list.stream ().filter ( detail -> detail.getDocNo ().equals ( pay.getDocNo () ) ).mapToDouble ( detail -> Double.parseDouble ( detail.getVerificationAmount () ) ).sum ();
            if ( Double.parseDouble ( pay.getActualMoney () ) > sum ) {
                resultPay.add ( pay );
            }
        } );
        KingPayableVerificationVo vo = new KingPayableVerificationVo ();
        vo.setKingInvoicePayableEntities ( resultPayable );
        vo.setKingFinancePayEntities ( resultPay );
        return vo;
    }

    /**
     * 匹配核销，应收/应付审核后有可能会触发匹配核销；收款/付款审核后也有可能触发匹配核销
     * 在后生成单据审核时触发匹配核销
     *
     * @param type：类型，为1表示应付付款核销单，后面两个id则表示应付单Id和付款单Id；未2时，则表示应收单Id和收款单Id
     * @param source：来源；1=应付单触发来的；2=付款单触发来的；3=应收单触发来的；4=收款单触发来的
     * @param id：单据Id，对应上面source字段，分别为对应单据的Id
     * @param orderIds：采购/销售订单Id
     * @return
     */
    @Override
    public AjaxResult matchVerify ( Integer type, Integer source, String id, List<String> orderIds ) {
        KingPayableReceivableVerificationEntity verificationEntity = new KingPayableReceivableVerificationEntity ();
        verificationEntity.setVerificationType ( 2 );
        List<KingPayableReceivableVerificationDetailEntity> verificationDetailEntities = new ArrayList<> ();
        KingPayableReceivableVerificationDetailEntity verifyByPay = new KingPayableReceivableVerificationDetailEntity ();
        KingPayableReceivableVerificationDetailEntity verifyByPayable = new KingPayableReceivableVerificationDetailEntity ();
        if ( type == 1 ) {
            verificationEntity.setType ( 1 );
            //应付付款核销单
            if ( source == 1 ) {
                // 通过采购订单找到付款单进行匹配核销
                List<KingFinancePayDetailEntity> list = iKingFinancePayDetailService.list ( new LambdaQueryWrapper<KingFinancePayDetailEntity> ().
                        in ( KingFinancePayDetailEntity :: getOrderId, orderIds ) );
                if ( list == null || list.size () <= 0 ) {
                    return AjaxResult.error ( "没有找到付款单，无法匹配核销！" );
                }
                KingFinancePayEntity payEntity = iKingFinancePayService.querySingleById ( list.get ( 0 ).getRelationId () );
                // 应付单请求来的匹配核销
                KingInvoicePayableEntity payableEntity = iKingInvoicePayableService.querySingleById ( id );
                SysDept sysDept = iSysDeptService.getById ( payEntity.getSettlementDeptId () );
                KingBaseCurrencyEntity one = iKingBaseCurrencyService.getOne ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getCode, sysDept.getStandardCurrencyCode () ) );
                verificationEntity.setSettlementCompany ( sysDept.getDeptName () );
                verificationEntity.setOwnCurrencyTitle ( one.getCurrencyName () );
                verificationEntity.setPayReceiptCompany ( sysDept.getDeptName () );
                //明细：付款单部分
                String amount = Double.parseDouble ( payEntity.getActualMoney () ) > Double.parseDouble ( payableEntity.getTotalTaxPrice () ) ? payableEntity.getTotalTaxPrice () : payEntity.getActualMoney ();
                verifyByPay.setDoc ( "付款单" ).setDocType ( payEntity.getDocTypeCode () ).setDocNo ( payEntity.getDocNo () ).setLineNumber ( list.get ( 0 ).getLineNumber () ).
                        setBizTime ( payEntity.getBusinessTime () ).setTransactionDeptTitle ( payEntity.getTransactionCompanyName () ).setCurrencyTitle ( payEntity.getSettlementCurrencyName () ).
                        setRate ( payEntity.getRate () ).setVerificationAmount ( amount ).setPayPurpose ( list.get ( 0 ).getPayReceiptPurposeCode () ).setMaterialName ( list.get ( 0 ).getMaterialCode () ).
                        setFeeItem ( list.get ( 0 ).getFeeCode () );
                //应付单部分
                verifyByPayable.setDoc ( "应付单" ).setDocType ( payableEntity.getDocTypeCode () ).setDocNo ( payableEntity.getDocNo () ).setLineNumber ( "1" ).setBizTime ( payableEntity.getBizTime () ).
                        setTransactionDeptTitle ( payableEntity.getSupplierName () ).setCurrencyTitle ( payableEntity.getCurrencyName () ).setRate ( payableEntity.getRate () ).setVerificationAmount ( amount );
                verificationDetailEntities.add ( verifyByPay );
                verificationDetailEntities.add ( verifyByPayable );
            } else if ( source == 2 ) {
                //付款单请求来的匹配核销，通过采购订单Id找应付单
                List<KingInvoicePayableDetailEntity> list = iKingInvoicePayableDetailService.list ( new LambdaQueryWrapper<KingInvoicePayableDetailEntity> ().
                        in ( KingInvoicePayableDetailEntity :: getSourceId, orderIds ) );
                if ( list == null || list.size () <= 0 ) {
                    return AjaxResult.error ( "没有找到应付单，无法匹配核销" );
                }
                KingInvoicePayableEntity payableEntity = iKingInvoicePayableService.querySingleById ( list.get ( 0 ).getInvoicePayableId () );
                KingFinancePayEntity payEntity = iKingFinancePayService.querySingleById ( id );
                //通过采购订单找应付单进行匹配核销
                SysDept sysDept = iSysDeptService.getById ( payEntity.getSettlementDeptId () );
                KingBaseCurrencyEntity one = iKingBaseCurrencyService.getOne ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getCode, sysDept.getStandardCurrencyCode () ) );
                verificationEntity.setSettlementCompany ( sysDept.getDeptName () );
                verificationEntity.setOwnCurrencyTitle ( one.getCurrencyName () );
                verificationEntity.setPayReceiptCompany ( sysDept.getDeptName () );
                //明细：
                String amount = Double.parseDouble ( payEntity.getActualMoney () ) > Double.parseDouble ( payableEntity.getTotalTaxPrice () ) ? payableEntity.getTotalTaxPrice () : payEntity.getActualMoney ();
                verifyByPay.setDoc ( "付款单" ).setDocType ( payEntity.getDocTypeCode () ).setDocNo ( payEntity.getDocNo () ).setLineNumber ( list.get ( 0 ).getLineNumber () ).
                        setBizTime ( payEntity.getBusinessTime () ).setTransactionDeptTitle ( payEntity.getTransactionCompanyName () ).setCurrencyTitle ( payEntity.getSettlementCurrencyName () ).
                        setRate ( payEntity.getRate () ).setVerificationAmount ( amount ).setPayPurpose ( payEntity.getPayReceiptPurposeCode () ).setMaterialName ( list.get ( 0 ).getMaterialCode () ).
                        setFeeItem ( list.get ( 0 ).getFeeCode () );
                //应付单部分
                verifyByPayable.setDoc ( "应付单" ).setDocType ( payableEntity.getDocTypeCode () ).setDocNo ( payableEntity.getDocNo () ).setLineNumber ( "1" ).setBizTime ( payableEntity.getBizTime () ).
                        setTransactionDeptTitle ( payableEntity.getSupplierName () ).setCurrencyTitle ( payableEntity.getCurrencyName () ).setRate ( payableEntity.getRate () ).setVerificationAmount ( amount );
                verificationDetailEntities.add ( verifyByPay );
                verificationDetailEntities.add ( verifyByPayable );
            }
        } else if ( type == 2 ) {
            verificationEntity.setType ( 2 );
            //应收收款核销单，此时处理应收单和收款单的匹配核销
            if ( source == 3 ) {
                // 应收单进来的，通过销售订单号找收款单
                List<KingFinanceReceiptDetailEntity> list = iKingFinanceReceiptDetailService.list ( new LambdaQueryWrapper<KingFinanceReceiptDetailEntity> ().
                        in ( KingFinanceReceiptDetailEntity :: getSaleOrderId, orderIds ) );
                if ( list == null || list.size () <= 0 ) {
                    return AjaxResult.error ( "没有找到收款单，无法匹配核销" );
                }
                KingFinanceReceiptEntity receiptEntity = iKingFinanceReceiptService.querySingleById ( list.get ( 0 ).getRelationId () );
                KingInvoiceReceivableEntity receivableEntity = iKingInvoiceReceivableService.querySingleById ( id );
                SysDept sysDept = iSysDeptService.getById ( receiptEntity.getSettlementDeptId () );
                KingBaseCurrencyEntity one = iKingBaseCurrencyService.getOne ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getCode, sysDept.getStandardCurrencyCode () ) );
                verificationEntity.setSettlementCompany ( sysDept.getDeptName () );
                verificationEntity.setOwnCurrencyTitle ( one.getCurrencyName () );
                verificationEntity.setPayReceiptCompany ( sysDept.getDeptName () );
                //明细
                String amount = Double.parseDouble ( receiptEntity.getActualMoney () ) > Double.parseDouble ( receivableEntity.getTotalTaxAmount () ) ? receivableEntity.getTotalTaxAmount () : receiptEntity.getActualMoney ();
                verifyByPay.setDoc ( "收款单" ).setDocType ( receiptEntity.getDocTypeCode () ).setDocNo ( receiptEntity.getDocNo () ).setLineNumber ( list.get ( 0 ).getLineNumber () ).
                        setBizTime ( receiptEntity.getBusinessTime () ).setTransactionDeptTitle ( receiptEntity.getTransactionCompanyName () ).setCurrencyTitle ( receiptEntity.getSettlementCurrencyName () ).
                        setRate ( receiptEntity.getRate () ).setVerificationAmount ( amount ).setPayPurpose ( list.get ( 0 ).getReceiptPurposeCode () ).setMaterialName ( list.get ( 0 ).getMaterialCode () ).
                        setFeeItem ( list.get ( 0 ).getFeeCode () );
                //应付单部分
                verifyByPayable.setDoc ( "应收单" ).setDocType ( receivableEntity.getDocTypeCode () ).setDocNo ( receivableEntity.getDocNo () ).setLineNumber ( "1" ).setBizTime ( receivableEntity.getBizTime () ).
                        setTransactionDeptTitle ( receivableEntity.getCustomerName () ).setCurrencyTitle ( receivableEntity.getCurrencyName () ).setRate ( receivableEntity.getRate () ).setVerificationAmount ( amount );
                verificationDetailEntities.add ( verifyByPay );
                verificationDetailEntities.add ( verifyByPayable );
            } else if ( source == 4 ) {
                //收款单进来的，通过销售订单Id拿到应收单
                List<KingInvoiceReceivableDetailEntity> list = iKingInvoiceReceivableDetailService.list ( new LambdaQueryWrapper<KingInvoiceReceivableDetailEntity> ().
                        in ( KingInvoiceReceivableDetailEntity :: getSourceId, orderIds ) );
                KingInvoiceReceivableEntity receivableEntity = iKingInvoiceReceivableService.querySingleById ( list.get ( 0 ).getInvoiceReceivableId () );
                KingFinanceReceiptEntity receiptEntity = iKingFinanceReceiptService.querySingleById ( id );
                SysDept sysDept = iSysDeptService.getById ( receiptEntity.getSettlementDeptId () );
                KingBaseCurrencyEntity one = iKingBaseCurrencyService.getOne ( new LambdaQueryWrapper<KingBaseCurrencyEntity> ().eq ( KingBaseCurrencyEntity :: getCode, sysDept.getStandardCurrencyCode () ) );
                verificationEntity.setSettlementCompany ( sysDept.getDeptName () );
                verificationEntity.setOwnCurrencyTitle ( one.getCurrencyName () );
                verificationEntity.setPayReceiptCompany ( sysDept.getDeptName () );
                //明细
                String amount = Double.parseDouble ( receiptEntity.getActualMoney () ) > Double.parseDouble ( receivableEntity.getTotalTaxAmount () ) ? receivableEntity.getTotalTaxAmount () : receiptEntity.getActualMoney ();
                verifyByPay.setDoc ( "收款单" ).setDocType ( receiptEntity.getDocTypeCode () ).setDocNo ( receiptEntity.getDocNo () ).setLineNumber ( list.get ( 0 ).getLineNumber () ).
                        setBizTime ( receiptEntity.getBusinessTime () ).setTransactionDeptTitle ( receiptEntity.getTransactionCompanyName () ).setCurrencyTitle ( receiptEntity.getSettlementCurrencyName () ).
                        setRate ( receiptEntity.getRate () ).setVerificationAmount ( amount ).setPayPurpose ( receiptEntity.getReceiptPurposeCode () ).setMaterialName ( list.get ( 0 ).getMaterialCode () ).
                        setFeeItem ( list.get ( 0 ).getFeeCode () );
                //应付单部分
                verifyByPayable.setDoc ( "应收单" ).setDocType ( receivableEntity.getDocTypeCode () ).setDocNo ( receivableEntity.getDocNo () ).setLineNumber ( "1" ).setBizTime ( receivableEntity.getBizTime () ).
                        setTransactionDeptTitle ( receivableEntity.getCustomerName () ).setCurrencyTitle ( receivableEntity.getCurrencyName () ).setRate ( receivableEntity.getRate () ).setVerificationAmount ( amount );
                verificationDetailEntities.add ( verifyByPay );
                verificationDetailEntities.add ( verifyByPayable );
            }
        }
        this.saveSingle ( verificationEntity, verificationDetailEntities );
        return AjaxResult.success ( "匹配核销完成" );
    }


    private void updateKingPayableVerificationDetail (List<KingPayableReceivableVerificationDetailEntity> kingPayableVerificationDetailEntities, String payableVerificationId ) {
        if ( ! CollectionUtils.isEmpty ( kingPayableVerificationDetailEntities ) ) {
            iKingPayableReceivableVerificationDetailService.remove ( new LambdaUpdateWrapper<KingPayableReceivableVerificationDetailEntity> ().eq ( KingPayableReceivableVerificationDetailEntity :: getRelationVerificationId, payableVerificationId ) );
            kingPayableVerificationDetailEntities.forEach ( detail -> {
                detail.setId ( SnowflakeIdWorker.getInstance ().nextStringId () );
                detail.setRelationVerificationId ( payableVerificationId );
                detail.setCreateBy ( SecurityUtils.getLoginUser ().getUser ().getUserId () );
                detail.setCreateTime ( DateUtils.getNowDate () );
                boolean save = iKingPayableReceivableVerificationDetailService.save ( detail );
                if ( ! save ) {
                    throw new CustomException ( "更新应付付款核销单明细失败！" );
                }
            } );
        }
    }

}
